package com.dq.repository.record;

import com.dq.domain.subscribe.Subscribe;

import com.dq.domain.org.Org;
import com.dq.domain.record.ServiceRecord;
import com.dq.domain.sys.user.user.StaffUser;
import com.dq.domain.sys.user.user.base.SysUser;
import com.dq.domain.sys.user.user.WxUser;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @Author luchangtong
 * @Date 2019/11/22 9:45
 */
@Repository
public interface ServiceRecordRepository extends JpaRepository<ServiceRecord, Long> {
    Long countByServiceStatusAndSysDeptAndDeletedFalse(ServiceRecord.ServiceStatus serviceStatus, Org sysDept);
    Long countByStaffUserAndServiceStatusAndDeletedFalse(SysUser sysUser, ServiceRecord.ServiceStatus serviceStatus);
    ServiceRecord getBySubscribe(Subscribe subscribe);
    Page<ServiceRecord> findByWxUserAndServiceStatusAndDeletedFalseOrderByCreateTimeDesc(SysUser sysUser, ServiceRecord.ServiceStatus status, Pageable pageable);
    Long countByWxUserAndServiceStatusAndDeletedFalse(SysUser sysUser, ServiceRecord.ServiceStatus status);
    Long countByWxUserAndServiceStatus(SysUser wxUser, ServiceRecord.ServiceStatus serviceStatus);

    List<ServiceRecord> findByWxUserAndServiceStatusAndDeletedFalse(SysUser sysUser, ServiceRecord.ServiceStatus serviceStatus);
    @Query("select COALESCE(sum(manualPrice),0) from ServiceRecord where staffUser = ?1 and serviceStatus =?2 and createTime>=?3 and createTime<=?4")
    BigDecimal manualPrice(StaffUser staffUser, ServiceRecord.ServiceStatus serviceStatus,Long beginTime,Long endTime);

    List<ServiceRecord> findBySubscribeAndDeletedFalse(Subscribe subscribe);

    List<ServiceRecord> findByServiceStatusInAndDeletedFalse(List<ServiceRecord.ServiceStatus> serviceStatus);


    List<ServiceRecord> findByWxUserAndSysDeptAndServiceStatusAndCreateTimeLessThanEqualAndCreateTimeGreaterThanEqualAndDeletedFalse(WxUser wxUser,Org org,ServiceRecord.ServiceStatus serviceStatus,Long beginTime,Long endTime);

    @Query(nativeQuery = true,value = "SELECT sum(sr.manual_price) manual_price,su.id,su.user_realc_name FROM `service_record` sr LEFT JOIN sys_user su \n" +
            "on\n" +
            "sr.staff_user_id = su.id\n" +
            "WHERE sr.create_time >= ?1 and sr.create_time <=?2  and sr.service_status=?3  and sys_dept_id=?4 \n" +
            "GROUP BY sr.staff_user_id ORDER BY sr.manual_price desc")
    List<Map> countManualPrice(Long beginTime,Long endTime,ServiceRecord.ServiceStatus serviceStatus,Long orgId);

    Long countByDeletedFalseAndServiceStatus(ServiceRecord.ServiceStatus serviceStatus);
}
